/*
 * @Author: linZeJian
 * @Date: 2022-01-27 16:09:58
 * @LastEditors: linZeJian
 * @LastEditTime: 2022-02-28 14:24:46
 * @Description:
 */
import axios from "axios";

const request = axios.create({
  timeout: 100000,
});

// 请求拦截器
request.interceptors.request.use(
  function (config:any) {
    return config;
  },
  function (error:any) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 相应拦截器
request.interceptors.response.use(
  function (response:any) {
    // 统一设置接口相应错误, 比如 token 过期失效, 服务端异常
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const errorCode = {
      "401": "认证失败，无法访问系统资源",
      "403": "当前操作没有权限",
      "404": "访问资源不存在",
      default: "系统未知错误，请反馈给管理员",
    };
    const msg = response.data.msg || errorCode[code] || errorCode["default"];
    if (code !== 200) {
      return Promise.reject("error");
    } else {
      return response.data;
    }
  },
  function (error:any) {
    // Do something with response error
    console.log("axios response 拦截器:" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    return Promise.reject(error);
  }
);

export default request;
